package cn.tedu._08weibo.controller;

import cn.tedu._08weibo.base.response.Result;
import cn.tedu._08weibo.base.response.StatusCode;
import cn.tedu._08weibo.mapper.UserMapper;
import cn.tedu._08weibo.pojo.dto.UserLoginParam;
import cn.tedu._08weibo.pojo.dto.UserRegParam;
import cn.tedu._08weibo.pojo.entity.User;
import cn.tedu._08weibo.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author tune_the last
 * @date 2025/11/17 - 18:42
 */
@Slf4j
@Tag(name = "用户模块")
@RestController
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @Operation(summary = "注册功能")
    @ApiOperationSupport(order = 10)
    @PostMapping("/reg")
    public Result userRegister(@RequestBody @Validated UserRegParam userRegParam){
        // 校验用户名输入：要求用户名长度为4-12位，且不允许连续出现3个及以上相同字符
        log.debug("userRegParam：" + userRegParam);
        //查询用户名是否存在
        int i = userMapper.selectUsernameIsExist(userRegParam.getUsername());
        if (i > 0){
            return Result.ok(StatusCode.USERNAME_EXIST.getMessage());
        }
        //写入数据库返回
        User user = new User();
        BeanUtils.copyProperties(userRegParam, user);
        user.setCreateTime(new Date());
        int j = userMapper.userRegister(user);
        if (j > 0){
            return Result.ok();
        }
        return Result.fail();
    }

    @Operation(summary = "登录功能")
    @ApiOperationSupport(order = 20)
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("UserLoginParam：" + userLoginParam);
        UserVO userVO = userMapper.userLogin(userLoginParam);
        if (userVO == null){
            return Result.fail(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        //向session中存储当前会话登录用户的数据
        session.setAttribute("user", userVO);
        return Result.ok(userVO);
    }

    @Operation(summary = "获取当前用户")
    @ApiOperationSupport(order = 30)
    @GetMapping("/currentUser")
    public Result getCurrentUser(HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        return Result.ok(userVO);
    }

    @Operation(summary = "退出登录")
    @ApiOperationSupport(order = 40)
    @GetMapping("/logout")
    public Result logout(HttpSession session){
        session.removeAttribute("user");
        return Result.ok();
    }
}
